/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.hiv.utils;

import com.hiv.config.ConfigurationConfig;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author zhanghong
 * @version WatermarkUtils.java, v 0.1 2022/5/30 17:08 下午 WatermarkUtils Exp $$
 */
public class WaterMarkUtils {

    /**
     * 添加水印
     *
     * @param visitUrl
     * @param waterMarkName
     * @return
     */
    public static String getWaterMarkPdfUrl(String visitUrl, String waterMarkName) {
        String inputFile = ConfigurationConfig.getAbsoluteFile(visitUrl);
        File file = new File(inputFile);
        String absolutePath = file.getParent();
        String outputFileName = file.getName();
        String[] split = outputFileName.split("\\.");
        outputFileName = split[0] + "_water_mark." + split[1];
        String outputFile = absolutePath + File.separator + outputFileName;
        WaterMarkUtils.addWaterMark(inputFile, outputFile, waterMarkName);
        return visitUrl.substring(0, visitUrl.lastIndexOf("/")) + File.separator + outputFileName;
    }

    /**
     * pdf添加水印
     * 参考文章
     * https://blog.csdn.net/winsanity/article/details/122624052
     *
     * @param inputFilePath  需要添加水印的文件
     * @param outputFilePath 添加完水印的文件存放路径
     * @return
     */
    public static boolean addWaterMark(String inputFilePath, String outputFilePath, String waterMarkName) {
        //水印字体透明度
        float opacity = 0.8f;
        //水印字体大小
        int fontsize = 40;
        //水印倾斜角度（0-360）
        int angle = 30;
        //数值越大每页竖向水印越少
        int heightDensity = 50;
        //数值越大每页横向水印越少
        int widthDensity = 10;

        File outputFile = new File(outputFilePath);
        if (outputFile.exists()) {
            outputFile.delete();
        }

        File inputFile = new File(inputFilePath);
        if (!inputFile.exists()) {
            return false;
        }

        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            int interval = -5;
            reader = new PdfReader(inputFilePath);
            stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            //这里是透明度设置
            gs.setFillOpacity(opacity);
            //这里是条纹不透明度
            gs.setStrokeOpacity(0.2f);
            int total = reader.getNumberOfPages() + 1;
            System.out.println("Pdf页数：" + reader.getNumberOfPages());
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            //字符串的高,   只和字体有关
            textH = metrics.getHeight();
            //字符串的宽
            textW = metrics.stringWidth(label.getText());

            // 设置字体 /华文宋体
            BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

            PdfContentByte under;
            //循环PDF，每页添加水印
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);  //在内容上方添加水印
                //under = stamper.getUnderContent(i);  //在内容下方添加水印

                // 设置颜色 默认为红色
                under.setColorFill(new BaseColor(204, 204, 204));
                under.setColorFill(BaseColor.RED);

                float fontSize = reader.getPageSizeWithRotation(1).getWidth()/2;
                fontSize = fontSize / 15;//动态计算字体大小
                System.out.println(String.format("fontSize=%s", fontSize));

                // 设置字体及字号
                under.setFontAndSize(font, fontSize);
                // 字符间距
                under.setCharacterSpacing(5);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //under.setColorFill(BaseColor.PINK);  //添加文字颜色  不能动态改变 放弃使用
                //under.setFontAndSize(base, fontsize); //这里是水印字体大小
                //for (int height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
                //    for (int width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
                //        // rotation:倾斜角度
                //        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, angle);
                //    }
                //}

                float height = reader.getPageSizeWithRotation(1).getHeight() * 0.95f;//文案居顶部
                float width = reader.getPageSizeWithRotation(1).getWidth() * 0.8f;//文案居中
                System.out.println(String.format("width=%s height=%s", width, height));
                under.showTextAligned(Element.ALIGN_CENTER, waterMarkName, width, height, 0);
                //添加水印文字
                under.endText();
            }
            System.out.println("添加水印成功！");
            return true;
        } catch (IOException e) {
            System.out.println("添加水印失败！错误信息为: " + e);
            e.printStackTrace();
            return false;
        } catch (DocumentException e) {
            System.out.println("添加水印失败！错误信息为: " + e);
            e.printStackTrace();
            return false;
        } finally {
            //关闭流
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                reader.close();
            }
        }
    }



    public static void main(String[] args) throws Exception {

        //需要添加水印的文件 width=1350.0 height=4390.9 font-size=100
        String inputFile = "/Users/zhanghong/Documents/gitee/hiv/invoice/39/20220601/506abf7ed4df5609f556880d96914362.pdf";
        //添加完水印的文件存放路径
        String outputFile = "/Users/zhanghong/Documents/gitee/hiv/invoice/39/20220601/506abf7ed4df5609f556880d96914362(水印).pdf";
        ////需要添加水印的文件 width=144.4 height=752.39996 font-size=30   150:30 5:1   1500
        //String inputFile = "/Users/zhanghong/Documents/gitee/hiv/invoice/39/20220601/72ab3a48c65a6af67b74561af3f2844d.pdf";
        ////添加完水印的文件存放路径
        //String outputFile = "/Users/zhanghong/Documents/gitee/hiv/invoice/39/20220601/72ab3a48c65a6af67b74561af3f2844d(水印).pdf";
        //需要添加的水印文字
        String waterMarkName = "06220005";
        //水印字体透明度
        float opacity = 0.3f;
        //水印字体大小
        int fontsize = 40;
        //水印倾斜角度（0-360）
        int angle = 30;
        //数值越大每页竖向水印越少
        int heightDensity = 50;
        //数值越大每页横向水印越少
        int widthDensity = 10;

        WaterMarkUtils.addWaterMark(inputFile, outputFile, waterMarkName);
    }
}
